import com.walkingfiles.registry.SignerType
import com.walkingfiles.registry.User
import com.walkingfiles.registry.Role
import com.walkingfiles.registry.UserRole
import com.walkingfiles.registry.Area
import com.walkingfiles.registry.Organization
import com.walkingfiles.registry.DocumentType
import com.walkingfiles.registry.FileType
import com.walkingfiles.registry.DocumentSubject
import com.walkingfiles.registry.DocumentState
import com.walkingfiles.registry.TransferSubject
import com.walkingfiles.registry.UserArea

class BootStrap {

    def init = { servletContext ->
		def role = null
		if (!Role.count()) {
			role = new Role(authority: 'ROLE_USER').save(failonError: true)
		}
		def user1, user2
		if (!User.count()) {
			user1 = new User(username: "mara", password: "mara", enabled: true).save(failOnError: true)
			new UserRole(user: user1, role: role).save(failOnError: true)
			user2 = new User(username: "ana", password: "ana", enabled: true).save(failOnError: true)
			new UserRole(user: user2, role: role).save(failOnError: true)
		}
		def org = null
		if (!Organization.count()) {
			println "Create new Organization"
			org = new Organization(name: 'sssalud', description: 'sssalud').save(failOnError: true)
		} else {
		    println "Find existing Organization"
		    org = Organization.get(0)
		}
		println "Org = ${org}"
		
		def area1, area2
		if (!Area.count()) {
			area1 = new Area(name: "Gerencia de Control Prestacional", 
				 	             description: "Gerencia de Control Prestacional",
					             organization: org).save(failOnError: true)
			println("Associating user: ${user1} with area: ${area1}")
		    new UserArea(user: user1, area: area1).save(failOnError: true)
			
			area2 = new Area(name: "Gerencia de Informatica", 
					             description: "Gerencia de Informatica",
					             organization: org).save(failOnError: true)
			println("Associating user: ${user2} with area: ${area2}")
		    new UserArea(user: user2, area: area2).save(failOnError: true)
		}
		
		
		if (!DocumentType.count()) {
			new DocumentType(name: 'Inscripcion').save(failOnError: true)
			new DocumentType(name: 'Afiliados').save(failOnError: true)
			new DocumentType(name: 'Comprobantes').save(failOnError: true)
		}
		if (!FileType.count()) {
			new FileType(name: 'PDF').save(failOnError: true)
			new FileType(name: 'TXT').save(failOnError: true)
			new FileType(name: 'DOC').save(failOnError: true)
		}
		if (!DocumentSubject.count()) {
			new DocumentSubject(name: 'Cargar').save(failOnError: true)
		}
		if (!SignerType.count()) {
			new SignerType(name: 'Signatario 1').save(failOnError: true)
		}
		if (!DocumentState.count()) {
			new DocumentState(name: 'N').save(failOnError: true)
		}
		if (!TransferSubject.count()) {
			new TransferSubject(name: 'Indexar').save(failOnError: true)
		}
    }
    def destroy = {
    }
}
